package com.jcli.fx3u;

import com.jcli.HslCommunication.Core.Types.OperateResult;
import com.jcli.HslCommunication.Core.Types.OperateResultExOne;
import com.jcli.HslCommunication.HslCommunicationDemo.DemoUtils;
import com.jcli.HslCommunication.Profinet.Melsec.MelsecA1ENet;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PLCDataReaderDemoWithSwing extends JFrame {
    private MelsecA1ENet melsecNet;
    private JTextArea textArea;
    private int readCount;
    private boolean isReading;
    private JPanel panelContent = null;        // 窗体的内容面板
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("[HH:mm:ss] ");

    public PLCDataReaderDemoWithSwing() {
        initializeUI();
    }

    private void initializeUI() {
        setTitle("PLC Data Reader with Swing");
        setSize(600, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panelConnect = new JPanel(new FlowLayout());

        JTextField ipTextField = new JTextField("192.168.1.11", 15);
        JTextField portTextField = new JTextField("3000", 5);
        JButton connectButton = new JButton("Connect");
        JButton disconnectButton = new JButton("Disconnect");

        disconnectButton.setEnabled(false);  // 初始化时禁用断开连接按钮
        connectButton.setEnabled(true);   // 初始化时启用连接按钮



        panelConnect.add(new JLabel("IP:"));
        panelConnect.add(ipTextField);
        panelConnect.add(new JLabel("Port:"));
        panelConnect.add(portTextField);
        panelConnect.add(connectButton);
        panelConnect.add(disconnectButton);




        JPanel createMainPanel = new JPanel(new BorderLayout());

        textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        createMainPanel.add(scrollPane, BorderLayout.CENTER);

        JButton readButton = new JButton("Read Data");
        JButton stopButton = new JButton("Stop Reading");

        readButton.setEnabled(false);
        stopButton.setEnabled(false);

        readButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startReading();
            }
        });

        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopReading();
            }
        });

        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(readButton);
        buttonPanel.add(stopButton);

        createMainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(panelConnect, BorderLayout.NORTH);
        add(createMainPanel, BorderLayout.CENTER);

        connectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                try {
                    melsecNet = new MelsecA1ENet();
                    melsecNet.setIpAddress(ipTextField.getText());
                    melsecNet.setPort(Integer.parseInt(portTextField.getText()));

                    OperateResult connect = melsecNet.ConnectServer();

                    if (connect.IsSuccess) {
                        JOptionPane.showMessageDialog(
                                null, "Connect Success", "Result", JOptionPane.PLAIN_MESSAGE);
                        DemoUtils.SetPanelEnabled(panelContent, true);

                        connectButton.setEnabled(true);  // 启用断开连接按钮
                        disconnectButton.setEnabled(false); // 禁用当前连接按钮，避免重复连接

                        readButton.setEnabled(false);
                        stopButton.setEnabled(false);


                    } else {
                        JOptionPane.showMessageDialog(
                                null, "Connect Failed:" + connect.ToMessageShowString(), "Result", JOptionPane.WARNING_MESSAGE);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            null, "Connect Failed\r\nReason:" + ex.getMessage(), "Result", JOptionPane.ERROR_MESSAGE);
                }

            }
        });

        disconnectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                disconnectPLC();
            }
        });

        // 将窗口设置为屏幕中央
        setLocationRelativeTo(null);

    }




    private void connectPLC(String ipAddress, int port) {

    }

    private void disconnectPLC() {
        if (melsecNet != null) {
            melsecNet.ConnectClose();
            DemoUtils.SetPanelEnabled(panelContent, false);
        }
    }

    private void startReading() {
        if (!isReading) {
            isReading = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isReading) {
                        readAndPrintData();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    private void stopReading() {
        isReading = false;
        disconnectPLC();
        textArea.append("停止读取\n");
    }

    private void readAndPrintData() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                textArea.append(dateFormat.format(new Date()) + "第 " + (++readCount) + " 次读取\n");

                //    读取并打印数据的逻辑提取为一个方法
                readAndPrintSingleData("D1");
                readAndPrintSingleData("D31");
                readAndPrintSingleData("D61");
                readAndPrintSingleData("D91");
                readAndPrintSingleData("D121");
                readAndPrintSingleData("D151");
                readAndPrintSingleData("D181");
                readAndPrintSingleData("D211");

                textArea.append("\n");
            }
        });
    }

    private void readAndPrintSingleData(String address) {
        OperateResultExOne<int[]> readResult7 = melsecNet.ReadInt32(address, (short) 30);
        if (readResult7.IsSuccess) {
            printIntArray(readResult7.Content);
        } else {
            textArea.append("读取失败\n");
        }
    }

    private void printIntArray(int[] data) {
        for (int value : data) {
            textArea.append(value + " ");
        }
        textArea.append("\n");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                PLCDataReaderDemoWithSwing demo = new PLCDataReaderDemoWithSwing();
                demo.setVisible(true);
            }
        });
    }
}
